<template>
    <!-- 对话框表单 -->
    <el-dialog class="ba-operate-dialog" :close-on-click-modal="false" :destroy-on-close="true"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)" @close="baTable.toggleForm">
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>

        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div class="ba-operate-form" :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'">
                <el-form ref="formRef" :model="baTable.form.items"  :rules="rules"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'" v-if="!baTable.form.loading">
                    <el-form-item prop="title" label="案例名称" >
                        <el-input v-model="baTable.form.items!.title"  type="string" placeholder="请输入案例名称"></el-input>
                    </el-form-item>
                    <el-form-item prop="title" label="案例副标题" >
                        <el-input v-model="baTable.form.items!.subtitle"  type="string" placeholder="请输入案例副标题"></el-input>
                        <span style="color:red">副标题是显示在案例名称下面的简短描述</span>
                    </el-form-item>
                    <FormItem label="所属分类" v-model="baTable.form.items!.nav_id" prop="nav_id" type="remoteSelect"
                        :input-attr="{
                            params: { isTree: false },
                            field: 'title',
                            'remote-url': '/admin/v1/page/product_type/category', onRow: onRemoteSelectRow, onSuccess: onSuccess,
                            placeholder: t('Click select'),
                        }" />
           
                    <FormItem label="案例图" type="images" :input-attr="{
                        hideSelectFile: true
                    }" v-model="baTable.form.items!.banner_path" />
                    <el-form-item label="封面图显示解释" >
                        <span style="color:red">上传图片尺寸是370x370的 第一张是370x370 也可以  因为系统会默认把第一张图片取为默认图片  前端布局才会一致</span>
                    </el-form-item>
                    <FormItem label="首页显示" v-model="baTable.form.items!.is_home" type="radio"
                        :data="{ content: { '0': '否', '1': '是' }, childrenAttr: { border: true } }" />
                  
                    <el-form-item label="首页显示解释" >
                        <span style="color:red">选择是的时候会在首页的精彩案例模块显示 反之则不显示</span>
                    </el-form-item>
                     <FormItem label="案例右侧" v-model="baTable.form.items!.is_right" type="radio"
                        :data="{ content: { '0': '否', '1': '是' }, childrenAttr: { border: true } }" />
                    <el-form-item label="案例右侧解释" >
                        <span style="color:red">选择是的时候会在精彩案例板块内容区域的右侧显示 只显示标题 反之则不显示</span>
                    </el-form-item>
                    <FormItem label="显示" v-model="baTable.form.items!.status" type="radio"
                        :data="{ content: { '0': '隐藏', '1': '显示' }, childrenAttr: { border: true } }" />
                    <el-form-item label="权重">
                        <el-input v-model="baTable.form.items!.weigh" type="number" placeholder="请输入权重"></el-input>
                    </el-form-item>
                    <FormItem label="内容" type="editor" v-model="baTable.form.items!.content" />
                  
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)"
                    type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') :
                        t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, inject, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import FormItem from '/@/components/formItem/index.vue'
import type { FormInstance, genFileId } from 'element-plus'
import { buildValidatorData } from '/@/utils/validate'
import { useConfig } from '/@/stores/config'
import { getQiniuToken } from '/@/api/backend/qiniu/index'
import * as qiniu from 'qiniu-js';
const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass
const { t } = useI18n()
const state = reactive({
    array: [{}],
})
const s_choose = ref('1')
const domainIndex = ref(0);
const dialogVisible = ref(false);
const qiniuArr = ref<any>([]);
//获取token
getQiniuToken().then(res => {
    if (res.code == 1) {
        qiniuArr.value = res.data
    }
})
const saveDomain = () => {
    console.log( baTable.form.items!.domains);
}

const addComber = (index: number) => {
    domainIndex.value = index
    dialogVisible.value = true
}


const addDomain = () => {
    baTable.form.items!.domains.push({
        key: '',
        value: '',
    })
}
//上传
const uploadFile = (params: any) => {
    const {file} = params
    // 获取当前时间戳
    const timestamp = Date.now();
    const originalFilename = file.name;
    const uniqueFilename = `${timestamp}_${originalFilename}`;
    const uptoken = qiniuArr.value.token
    // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
    const subObject = {
        next: next,
        error: error,
        complete: complete
    };
    //上传
    const key = uniqueFilename;
    const config = {
        chunkSize: 4 * 1024 * 1024, // 分块大小  
        useCdnDomain: true,
        region: qiniu.region.z0,
        forceDirect: true // 是否上传全部采用直传方式
    };
    const putExtra: any = {
        fname: originalFilename, //file.raw.name文件原文件名
        mimeType: [] //用来限制上传文件类型，为 null 时表示不对文件类型限制；
    };
    let observable = qiniu.upload(file, key, uptoken, putExtra, config);
    observable.subscribe(subObject);
}
const total = ref<any>([]);
const ispercent = ref(false)
//分片上传返回response，标记上传进度
const next = (response: any) => {
    total.value = response.total;
    ispercent.value = true
};
const error = (err: any) => {
    alert(err.message);
};
const iscomplete = ref(false)
const complete = (res: any) => {
    baTable.form.items!.download_url = res.key;
    iscomplete.value = true

};
const handleChangeOther = (file: any) => {
    const uptoken = qiniuArr.value.token
    // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
    const subObject = {
        next: nextOther,
        error: errorOther,
        complete: completeOther
    };
    //上传
    const key = file.raw.name;
    const config = {
        chunkSize: 4 * 1024 * 1024, // 分块大小  
        useCdnDomain: true,
        region: qiniu.region.z0,
        forceDirect: true // 是否上传全部采用直传方式
    };
    const putExtra: any = {
        fname: file.raw.name, //文件原文件名
        mimeType: [] //用来限制上传文件类型，为 null 时表示不对文件类型限制；
    };
    let observable = qiniu.upload(file.raw, key, uptoken, putExtra, config);
    observable.subscribe(subObject);
}


const totalOther = ref<any>([]);
const ispercentOther = ref(false)
//分片上传返回response，标记上传进度
const nextOther = (response: any) => {
    totalOther.value = response.total;
    ispercentOther.value = true
};
const errorOther = (err: any) => {
    alert(err.message);
};
const iscompleteOther = ref(false)
const completeOther = (res: any) => {
    baTable.form.items!.download_url_other = res.key;
    iscompleteOther.value = true

};
const isShow = ref(false)

const onRemoteSelectRow = (row: any) => {
    isShow.value = row.ascription == 1 ? true : false;
    baTable.form.items!.ascription = row.ascription;
}

const onSuccess = () => {
    console.log(123)
}
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    title: [buildValidatorData({ name: 'required', title: '产品名称不能为空' })],
    nav_id: [buildValidatorData({ name: 'required', message: t('Please select field', { field: '分类不能为空' }) })],
   
})

</script>

<style scoped lang="scss"></style>
